package com.cxs.strategy.spring;

import com.cxs.strategy.simple.LoginStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: cxs
 */
@Component
public class StrategyFactory implements ApplicationContextAware {

    //    @Autowired 也可以直接通过注解 默认key就是bean的名字
    private Map<String, LoginStrategy> loginStrategyMap = new ConcurrentHashMap<>();

    public Object realDoLogin(String loginStrategy, String username, String pwd) {
        LoginStrategy strategy = loginStrategyMap.get(loginStrategy);
        if (!ObjectUtils.isEmpty(strategy)) {
            return strategy.doLogin(username, pwd);
        }
        return null;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, LoginStrategy> strategyMap = applicationContext.getBeansOfType(LoginStrategy.class);
        strategyMap.forEach((beanName, strategy) -> {
            loginStrategyMap.put(beanName, strategy);
        });
    }
}
